import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/http/Res.dart';
import 'package:ladder_cash/app/com/plugin/face_plugin.dart';
import 'package:ladder_cash/app/com/service/burial_point_service.dart';
import 'package:ladder_cash/app/com/util/image_select_utils.dart';
import 'package:ladder_cash/app/com/view/common_view.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/date_mode.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/pduration.dart';
import 'package:ladder_cash/app/com/view/my_date_picker.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/page/component/common.dart';
import 'package:ladder_cash/generated/assets.dart' as myAssets;
import 'package:ladder_cash/generated/l10n.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:ladder_cash/value/app_const.dart';
import 'package:ladder_cash/value/app_lstyle.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liuxlcommon/util/re_click.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:liuxlcommon/view/extension_widget.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';

import '../../../../config/super_theme.dart';
import '../../../../gen/assets.gen.dart';
import '../../../../library/src/logger.dart';
import '../../component/decoration_bg.dart';
import '../authentication_logic.dart';

class IdInformationPage extends StatefulWidget {
  IdInformationPage({super.key});

  @override
  _AuthenticationPageState createState() => _AuthenticationPageState();
}

class _AuthenticationPageState extends State<IdInformationPage> {
  final logic = Get.find<AuthenticationLogic>();

  static Map<String, String> defaultImgs = {
    // 'pan'.hx: Assets.bgImgPan,
    'id_front'.hx: Assets.cer.cer1.path,
    'liveness'.hx: Assets.cer.cer2.path
  };

  @override
  Widget build(BuildContext context) {
    Logger.d("IdInformationPage");
    return LoadingView(
      isPullDown: true,
      future: () => logic.getIdInfo(),
      datas: logic.authenticationInfo,
      onSuccess: () {
        if (logic.authenticationInfo != null) logic.update();
      },
      body: () => LFlexV(
        [
          // LText("Please fill in your personal data (don't worry, your\ninformation and data are protected)")
          //     .css('''
          //         padding:12px;font-size: 13px;
          //         width: 375px;
          //         color:#F19B33;background: #FEF2CF; '''),
          12.lsh,
          LColumn.eazy([
            <Widget>[
              // itemView('pan'.hx),
              itemView('id_front'.hx),
              20.lsh,
              itemView('liveness'.hx),
            ].columnSlidExpand,
            Container(
              height: 46.w,
              child: commonBtn(S.current.next, callback: () {
                if (StringUtils.isEmpty(keyToImg('id_front'.hx))) {
                  dialogTip(context, 'id_front'.hx);
                } else if (StringUtils.isEmpty(keyToImg('liveness'.hx))) {
                  dialogTip(context, 'liveness'.hx);
                } else {
                  logic.saveNext();
                }
              }),
            ),
            LSizeH(42.w)
          ]).css('''flex:1;width:343px;'''),
        ],
      ).size(375.w, null),
    );
  }

  Map keyMap = {
    'id_front'.hx: 'id_number_z_picture'.hx,
    'liveness'.hx: 'face_recognition_picture'.hx
  };
  Map txtmap = {
    // "id_front1": S.current.rzIdTxtPanCard,
    // 'pan'.hx: S.current.rzIdTxtPanCard,
    'id_front'.hx: S.current.panCard,
    'liveness'.hx: S.current.faceRecognition
  };

  String? keyToImg(String key) {
    return logic.authenticationInfo?[key]?['url'.hx];
    // if (key == 'id_front'.hx) {
    //   return logic.authenticationInfo?['item'.hx]?['id_number_z_picture'.hx];
    // } else if (key == 'liveness'.hx) {
    //   return logic.authenticationInfo?['item'.hx]?['face_recognition_picture'.hx];
    // }
    // return null;
  }

  Widget itemView(key) {
    String url = StringUtils.defaultValue(keyToImg(key), defaultImgs[key]);
    bool isRz = !StringUtils.isEmpty(keyToImg(key));
    return <Widget>[
      LImage.easy(url, 174.w, 279.w, 10.w),
      10.lsh,
      LText.easy(txtmap[key], 16.w, FontWeight.bold, AppColors.textColor),
    ].column.css('''width: 343px;
padding:12px; 16px;
background: #FFFFFF;
border-radius: 16px 16px 16px 16px;''').onTapL(() {
      dialogTip(context, key);
    });
  }

  dialogTip(context, key) {
    if (!clickable()) return;
    if (StringUtils.isNotEmpty(keyToImg(key))) return;
    if (key == 'pan'.hx) {
      BurialPointService.start(BPoint.idPan);
      CommonView.idPanDialog(() async {
        Get.back();
        Map? map = await ImageSelectUtils.getFileImagePath();
        if (map != null) {
          logic.informationService
              .uploadImgAndIde(map['path'], spot: map['mode'], height1: 13)
              .then((value) {
            if (value == null) return;
            // if ((value['is_need_pop'.hx] ?? 1) == 1) {
            //   idRzFrontDialog(value);
            // } else {
            //   BurialPointService.end(BPoint.idPan);
            //   logic.authenticationInfo = null;
            //   logic.update();
            // }
            BurialPointService.end(BPoint.idPan);
            logic.authenticationInfo = null;
            logic.update();
          });
        }
      });
    } else if (key == 'id_front'.hx) {
      // if (StringUtils.isEmpty(logic.authenticationInfo?['pan']?["url"])) {
      //   ToastUtils.toast(S.current.rzIdPanToast);
      //   return;
      // }
      BurialPointService.start(BPoint.idFront);
      CommonView.idFrontDialog(
          title: S.current.panCard,
          isFace: false,
          message: S.current.pleaseSubmit, () async {
        Get.back();
        var map = await ImageSelectUtils.getFileImagePath();
        Logger.d(map);
        if (map != null) {
          logic.informationService
              .uploadImgAndIde(map['path'], spot: map['mode'], height1: 11)
              .then((value) {
            if (value == null) return;
            if ((value['is_need_pop'.hx] ?? 0) == 1) {
              idRzFrontDialog(value);
              // Get.to(IdFrontConfirmEditPage(logic.title, value))?.then((value) {
              //   if (value) {
              //     logic.authenticationInfo = null;
              //     logic.update();
              //   }
              // });
            } else {
              BurialPointService.end(BPoint.idFront);
              logic.authenticationInfo = null;
              logic.update();
            }
          });
        }
      });
    } else if (key == 'id_back') {
      // if (StringUtils.isEmpty(logic.authenticationInfo?['pan']?["url"])) {
      //   ToastUtils.toast(S.current.rzIdPanToast);
      //   return;
      // }
      if (StringUtils.isEmpty(
          logic.authenticationInfo?['id_front'.hx]?['toes'.hx])) {
        // ToastUtils.toast(S.current.rzIdFrontToast);
        return;
      }

      BurialPointService.start(BPoint.idBack);
      CommonView.idBackDialog(() async {
        Get.back();
        Map? map = await ImageSelectUtils.getFileImagePath();
        if (map != null) {
          logic.informationService
              .uploadImgAndIde(map['path'], spot: map['mode'], height1: 12)
              .then((value) {
            BurialPointService.end(BPoint.idBack);
            logic.authenticationInfo = null;
            logic.update();
          });
        }
      });
    } else if (key == 'liveness'.hx) {
      Logger.d("99999999");
      if (StringUtils.isEmpty(keyToImg('id_front'.hx))) {
        // ToastUtils.toast(S.current.rzIdPanToast);
        lastPopTime = null;
        dialogTip(context, 'id_front'.hx);
        return;
      }
      // if (StringUtils.isEmpty(logic.authenticationInfo?['pan']?["url"])) {
      //   ToastUtils.toast(S.current.rzIdFrontToast);
      //   return;
      // }
      BurialPointService.start(BPoint.face);
      CommonView.idFrontDialog(
          title: S.current.faceRecognition,
          isFace: true,
          message: S.current.pleaseFollow, () async {
        // Get.to(IdtipPage('liveness'.hx, () async {
        Get.back();

        ///face++---------
        // var data = await HttpRequest().post("/kini/oplaey", <String, dynamic>{},
        //     loadingText: S.current.loading);
        // if (data != null) {
        //   dynamic ttt = await FacePlugin.faceAdd(data['opol']!, data['qwty']!);
        //   if (StringUtils.isNotEmpty(ttt['data'.hx]?['jake'])) {
        //     logic.authenticationInfo = null;
        //     logic.update();
        //   }
        // }
        ///--------------

        // String? path = await FacePlugin.getFacePath;
        String? path = (await ImageSelectUtils.getFileImagePath(
            preferredCameraDevice: CameraDevice.front))?["path"];
        if (path != null) {
          BurialPointService.end(BPoint.face);
          logic.informationService
              .uploadImgAndIde(path, spot: 0, height1: 10)
              .then((value) {
            logic.authenticationInfo = null;
            logic.update();
          });
        }
      });
    }
  }

  idRzFrontDialog(data) {
    Logger.d(data);
    Map<String, dynamic> myData = {};
    myData['name'.hx] = data['idcard_name'.hx];
    myData['id_number'.hx] = data['idcard_num'.hx];
    myData['type'.hx] = 11;
    myData['birthday'.hx] = data['birthday'.hx] ?? '';
    Get.dialog(Column(
      children: [
        Expanded(
          child: Container(),
        ),
        SizedBox(
          height: 600.w,
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                height: 30.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Image.asset(
                        Assets.cer.cerClose.path,
                        width: 30.w,
                        height: 30.w,
                      ),
                    ),
                  ],
                ),
              ),
              30.lsh,
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20.w),
                padding: EdgeInsets.only(
                    left: 20, right: 20.w, bottom: 10.w, top: 40.w),
                height: 540.w,
                decoration: BoxDecoration(
                    image: getDecorationBg(Assets.cer.cerPanBg.path)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    textBorder("Information confirmation",
                        fontWeight: FontWeight.w900,
                        fontsize: 24.sp,
                        color: SuperTheme.textTitltPrimary,
                        borderColor: Colors.black,
                        fontFamily: 'italic'),
                    LColumn.eazy([
                      10.lsh,
                      itemInput(S.current.fullName, data['idcard_name'.hx],
                          myData['name'.hx], (txt) => myData['name'.hx] = txt),
                      itemInput(
                          S.current.idNo,
                          data['idcard_num'.hx],
                          myData['id_number'.hx],
                          (txt) => myData['id_number'.hx] = txt),
                      12.lsh,
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                        middleFont(S.current.birthday),
                      ],),
                      12.lsh,
                      itemDate(myData, data['birthday'.hx], S.current.birthday,
                          myData['birthday'.hx], callback: (bir) {
                        myData['birthday'.hx] = bir;
                      }),
                      12.lsh,
                      middleFont(S.current.pleaseVerify,
                          color: Colors.red, fontsize: 12.sp)
                    ]).onTapL(() => OldLInput.unfocus()).size(271.w, null),
                    Container(
                        height: 46.w,
                        child: commonBtn(S.current.confirm, callback: () async {
                          BurialPointService.end(BPoint.idFront);
                          Res r = await HttpRequest().postRes(
                              '/v3/certify/save-basic-info', myData,
                              loadingText: S.current.loading);
                          if (r.success) {
                            Get.back();
                            logic.authenticationInfo = null;
                            logic.update();
                          }
                        })),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(child: Container())
      ],
    ));
    // CommonView.commDialog(
    //     title: "Information confirmation",
    //     height: 439.w,
    //     message: data['confirmStr'.hx],
    //     confirm: () async {
    //       BurialPointService.end(BPoint.idFront);
    //       Res r = await HttpRequest().postRes(
    //           '/v3/certify/save-basic-info',
    //           <String, dynamic>{
    //             'product_id'.hx: data['product_id'],
    //             data['confirmList'.hx][0]['code'.hx]: data['name'.hx],
    //             data['confirmList'.hx][1]['code'.hx]: data['id_card_number'.hx],
    //             data['confirmList'.hx][2]['code'.hx]: data['birthday'.hx],
    //             'card_type'.hx: data['card_type'.hx],
    //             "type": 11,
    //           },
    //           loadingText: S.current.loading);
    //       if (r.success) {
    //         Get.back();
    //         logic.authenticationInfo = null;
    //         logic.update();
    //       }
    //     },
    //     children: [
    //       LColumn.eazy([
    //         10.lsh,
    //         itemInput(
    //             data['confirmList'.hx][0]['titleStr'.hx],
    //             data['confirmList'.hx][0]['titleStr'.hx],
    //             data['name'.hx],
    //             (txt) => data['name'.hx] = txt),
    //         itemInput(
    //             data['confirmList'.hx][1]['titleStr'.hx],
    //             data['confirmList'.hx][1]['titleStr'.hx],
    //             data['id_card_number'.hx],
    //             (txt) => data['id_card_number'.hx] = txt),
    //         itemDate(data, data['confirmList'.hx][2]['titleStr'.hx], '',
    //             data['birthday'.hx]),
    //         12.lsh,
    //       ]).onTapL(() => OldLInput.unfocus()).size(271.w, null),
    //     ]);
  }

  get editInputCss => '''
  width: 311px;
background: #FFFFFF;
padding:10px 16px;
margin-bottom:15px;
border-radius: 12px; ''';

  itemInput(title, hint, value, onChange(text)) => LColumn.eazy([
        LRow.eazy([
          // LContainer()
          //     .bgColor(AppColors.primaryColor)
          //     .radius(3.5.w)
          //     .size(7.w, 15.w),
          // 13.lsw,
          LText.easy(title, 14.sp, fw6, const Color(0xFF333333)).flex(1),
        ]).size(null, 42.w),
        LInput(value,
            lStyle: LStyle(
                hintColor: AppColors.textHintColor,
                alignment: Alignment.centerLeft,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                css: '''width: 271px; 
height: 45px;padding-left:20px;background: #F6F8F9;
border-radius: 10px;'''),
            lInputType: LInputType.TEXT, onChanged: (txt) {
          onChange(txt);
        })
      ]).size(271.w, null);

  itemDate(data, title, hint, value,
          {required Function? Function(String birthday) callback}) =>
      LColumn.eazy([
        GetBuilder<AuthenticationLogic>(
            id: 'dialogdate',
            builder: (l) => Column(
                  children: [

                    LText(
                      StringUtils.defaultValue(
                          data['birthday'.hx], S.current.dateBirth),
                      lStyle: LStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                          alignment: Alignment.centerLeft,
                          css: '''width: 271px;
height: 45px;padding-left:20px;background: #F6F8F9;
border-radius: 10px;''')
                        ..color = StringUtils.isEmpty(data['birthday'.hx])
                            ? AppColors.textSecondColor
                            : AppColors.textColor
                        ..hintText = S.current.birthdateTitle,
                      onTap: () {
                        MyDatePicker().showDatePicker(logic.context,
                            selectTxt: data['birthday'.hx] ??
                                (data['birthday'.hx] ?? ""),
                            onConfirm: (txt, PDuration p) {
                          data['birthday'.hx] = txt;
                          callback(txt);
                          l.update(['dialogdate']);
                        }, model: DateMode.YMD);
                      },
                    )
                  ],
                ))
      ]).size(271.w, null);

  get itemTitleSty => LStyle(
      margin: EdgeInsets.only(top: 15.w, bottom: 5.w),
      fontSize: 15.sp,
      fontWeight: fw4,
      width: 264.w);

  LStyle get inputSty => LStyle(
        css: '''
      width: 264px;height: 48px;
border-radius: 16px;
padding:0 16px;background: #FFFFFF;
      ''',
        hintColor: Color(0xFFCAC7CD),
        alignment: Alignment.centerLeft,
        color: 0xFFF010B0.color,
        fontSize: 15.w,
      );
}
